<template>
  <div class="navbar" :class="{ 'small-search-box': useClass == 'fixed-show' }">
    <div class="container width_1200_auto flex flex-a-c flex-j-sb">
      <img
        :src="$store.state.logoImg"
        v-if="showLogo"
        class="logo-img"
        alt=""
        @click="$router.push('/')"
      />
      <!--div
        class="common_nav"
        style="
          align-items: left;
          width: 550px;
          height: 36px;
          line-height: 36px;
          margin-top: 15px;
        "
      >
        <ul>
          <li id="channel_1">
            <a href="#"><i class="iconfont icon-yuandian"></i>首页</a>
          </li>
          <li id="channel_8">
            <a href="#" target="_blank">
              <i class="iconfont icon-yuandian"></i>出境游<img src="@/assets/images/top_nav_bg8.png" />
            </a>
          </li>
          <li id="channel_17" class="nav_more">
            <a href="#" target="_blank">
              <i class="iconfont icon-yuandian"></i>国内游<img src="@/assets/images/top_nav_bg9.png"/>
            </a>
            <div class="nav_a">
              <div class="nav_item">
                <a href="https://www.uzai.com/JointWork/Login" target="_blank"><span>中信银行贵宾</span></a>
                <a href="https://www.uzai.com/JointWork/MinshengLogin" target="_blank"><span>民生银行贵宾</span></a>
              </div>
            </div>
          </li>
          <li id="channel_2048" class="nav_more">
            <a href="http://event.uzai.com/subject/bjdkh/dkh.htm" target="_blank">
              <i class="iconfont icon-yuandian"></i>大客户专区<i class="iconfont icon-zhankai"></i>
            </a>
            <div class="nav_a">
              <div class="nav_item">
                <a href="https://www.uzai.com/JointWork/Login" target="_blank"
                  ><span>中信银行贵宾</span></a
                ><a
                  href="https://www.uzai.com/JointWork/MinshengLogin"
                  target="_blank"
                  ><span>民生银行贵宾</span></a
                >
              </div>
            </div>
          </li>
        </ul>
      </div-->
      <Menu mode="horizontal" class="top-menu" theme="light" @on-select="onSelect" ref='menu'>
        <MenuItem name="0"  @click="goGoodsList(0, 0)" class="ivu-menu-submenu">
          <div class="ivu-menu-submenu-title" style="margin-right: 30px;">
            <Icon type="ios-home" style="color:#f02e4c; font-size: 24px; font-weight: 500;"/>首页
          </div>
        </MenuItem>
        <Submenu :name="index+1" v-for="(menu, index) in cateListReverse()" :key="index">
          <template #title>
            <Icon :type="categoriesType[index]" style="color:#f02e4c; font-size: 24px; font-weight: 500;"/>{{ menu.name }}
          </template>
          <MenuItem
            v-for="(chlidren, i) in cateList"
            :key="i"
            :name="chlidren.id"
            class="ivu-menu-opened"
            v-if="!!chlidren.fatherid && menu.id == chlidren.fatherid"
            @click="goGoodsList(chlidren.id, chlidren.fatherid)" 
            >{{ chlidren.name }} </MenuItem
          >
        </Submenu>
      </Menu>

      <div :class="{ 'small-search-box': useClass == 'fixed-show' }" class="search-box" >
        <i-input
          v-model="searchData"
          size="large"
          class="search"
          placeholder="输入你想查找的产品"
          @keyup.enter.native="search"
        >
          <div class="search-icon" slot="append" @click="search">
            <Icon type="ios-search" size="21" />
          </div>
        </i-input>
        <template v-if="showTag">
          <!--div class="only-store" v-if="storeId" @click="research()">
            切换为{{ !onlyStore ? "店铺内" : "平台" }}搜索
          </div>
          <div v-if="promotionTags.length === 0"></div>
          <div v-else class="history-list flex">
            <div
              v-for="(item, index) in promotionTags"
              :key="index"
              class="mr_10"
            >
              <span class="history-item" @click="selectTags(item)">{{
                item
              }}</span>
            </div>
          </div-->
        </template>
      </div>
    </div>

  </div>
</template>

<script>
import storage from "@/plugins/storage.js";
import { hotWords } from "@/api/goods.js";
import { menuCategories } from "@/api/index.js";

export default {
  name: "search",
  props: {
    showTag: {
      // 是否展示搜索栏下方热门搜索
      type: Boolean,
      default: true,
    },
    showLogo: {
      // 是否展示左侧logo
      type: Boolean,
      default: true,
    },
    storeId: {
      // 是否为店铺页面
      type: String,
      default: "",
    },
    hover: {
      type: Boolean,
      default: false,
    },
    useClass: {
      type: null,
      default: "",
    },
  },
  watch: {
    storeId(val) {
      this.onlyStore = val ? true : false;
    },
  },
  data() {
    return {
      searchData: "", // 搜索内容
      onlyStore: false,
      cateList: [],
      categoriesType: [
        'md-leaf',
        'md-medal',
      ],
    };
  },
  methods: {
    selectTags(item) {
      // 选择热门标签
      this.searchData = item;
      this.search();
    },

    research() {
      this.onlyStore = !this.onlyStore;
    },

    search() {
      if (!this.searchData) {
        return false
      }
      // 全平台搜索商品
      const url = this.$route.path;
      if (url == "/goodsList") {
        this.$emit("search", this.searchData);
      } else {
        const pushData = {
          path: "/goodsList",
          query: { title: this.searchData },
        };
        // 店铺内搜索
        if (this.storeId && this.onlyStore) {
          pushData.query.storeId = this.storeId;
        }

        this.$router.push(pushData);
      }
    },

    searchStore() {
      // 店铺搜索商品
      this.$emit("search", this.searchData);
    },

    // 导航分类
    getCate() {
      // 获取分类数据
      if (this.hover) return false;
      menuCategories().then((res) => {
        if (res.success) {
          this.cateList = res.result;
          this.$store.commit("SET_CATEGORY", res.result);
          // 过期时间
          //var expirationTime = new Date().setHours(new Date().getHours() + 1);
          // 存放过期时间
          //localStorage.setItem("category_expiration_time", expirationTime);
          // 存放分类信息
          //localStorage.setItem("category", JSON.stringify(res.result));
        }
      });
    },

    //倒序
    cateListReverse() {
      // 此操作防止改变原数据造成vue渲染死循环
      // let data = JSON.parse(JSON.stringify(this.cateList));
      let array = [];
      // data.reverse().forEach((item, index) => {
      //   if (item.fatherid == null && item.orders < 30) {
      //     array.push(item);
      //   }
      // })
      //console.info("cateListReverse@@@@", array)
      return array;
    },

    /**
     * 菜单打开
     * @param id 
     */
    goGoodsList(id, secondId, firstId) {
      console.info(id, secondId, firstId, (!secondId ))
      if ((typeof firstId == "undefined" || !firstId) && (typeof secondId == "undefined" || !secondId)) {
        return
      }
      // 分类共有三级，传全部分类过去
      const arr = [firstId, secondId, id];
      if (!arr[1]) {
        arr.splice(0, 2);
      }
      if (!arr[0]) {
        arr.shift();
      }
      let routerUrl = this.$router.resolve({
        path: "/goodsList",
        query: {
          categoryId: arr.toString()
        },
      });
      window.open(routerUrl.href, "goGoodsList");
    },

    // 每次点击左侧bar的callback
    onSelect (id) {
      if (id == '0') {
        var protocol = window.location.protocol;
        var host = window.location.host;
        var currentUrl = protocol + '//' + host;
        console.log(currentUrl);
        window.open(currentUrl, "_self");
      } else {
        var menu = this.cateList.filter(item => item.id == id )
        if (menu.length > 0) {
          this.goGoodsList(menu[0].id, menu[0].fatherid)
          this.detail = ''
          this.showList = true
        }
      }
    },

    /**
     * 菜单打开
     * @param id 
     */
     goGoodsList(id, secondId, firstId) {
      console.info(id, secondId, firstId, (!secondId ))
      if ((typeof firstId == "undefined" || !firstId) && (typeof secondId == "undefined" || !secondId)) {
        return
      }
      // 分类共有三级，传全部分类过去
      const arr = [firstId, secondId, id];
      if (!arr[1]) {
        arr.splice(0, 2);
      }
      if (!arr[0]) {
        arr.shift();
      }
      let routerUrl = this.$router.resolve({
        path: "/goodsList",
        query: {
          categoryId: arr.toString()
        },
      });
      window.open(routerUrl.href, "_blank");
    },

  },
  computed: {
    promotionTags() {
      if (this.$store.state.hotWordsList) {
        return JSON.parse(this.$store.state.hotWordsList);
      } else {
        return [];
      }
    },
  },
  created() {
    this.searchData = this.$route.query.keyword;

    if (!this.hover) {
      // 首页顶部固定搜索栏不调用热词接口
      // 搜索热词每5分钟请求一次
      const reloadTime = storage.getItem("hotWordsReloadTime");
      const time = new Date().getTime() - 5 * 60 * 1000;
      if (!reloadTime) {
        hotWords({ count: 5 }).then((res) => {
          if (res.success && res.result)
            storage.setItem("hotWordsList", res.result);
        });
        storage.setItem("hotWordsReloadTime", new Date().getTime());
      } else if (reloadTime && time > reloadTime) {
        hotWords({ count: 5 }).then((res) => {
          if (res.success && res.result)
            storage.setItem("hotWordsList", res.result);
        });
        storage.setItem("hotWordsReloadTime", new Date().getTime());
      }
    }

    if ( localStorage.getItem("category") && localStorage.getItem("category_expiration_time") ) {
      // 如果缓存过期，则获取最新的信息
      if (new Date() > localStorage.getItem("category_expiration_time")) {
        this.getCate();
        return;
      }
      this.cateList = JSON.parse(localStorage.getItem("category"));
    } else {
      //this.getCate();
    }

    //console.info("search@@@@@@@@@created")
    //this.handleMenuCategories();
  },
};
</script>

<style scoped lang="scss">
@import '~@/assets/font/iconfont0/iconfont.css';
a {
  text-decoration: none;
  color: #000;
}
.only-store {
  text-align: right;
  color: $theme_color;
  cursor: pointer;
}
.navbar {
  height: 80px;
  background: #fff;
  border-bottom: 3px $color-primary solid;
}

.search-icon {
  width: 100%;
  height: 100%;
}
.small-search-box {
  height: 60px;
  margin: 0 !important;
}

.container {
  position: relative;
  height: 100%;
}

.search {
  width: 350px;
  margin: 10px 0px 5px 0;
  border-radius: 18.9px;

  ::v-deep .ivu-input.ivu-input-large {
    border: 1.4px solid $theme_color;
    box-sizing: border-box;
    border-radius: 19.6px;
    position: relative;
    padding-left: 26px;
    font-size: 14px;
    font-weight: normal;
    height: 37.8px;
    color: #999;
    &:focus {
      box-shadow: none;
    }
  }

  ::v-deep .ivu-input-group-append {
    border-radius: 19.6px !important;
    cursor: pointer;
    box-sizing: border-box;
    border: 1.4px solid $theme_color;
    width: 67.2px;
    height: 37.8px;
    position: absolute;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    top: 0;
    z-index: 99;
    background-color: $theme_color;
    color: #ffffff;

    button {
      font-size: 14px;
      font-weight: 600;
      line-height: 1;
    }
  }
}

.icon-feiji {
  position: relative;
  top: 2px;
}

.search-box {
  margin-left: 28px;
}

.logo-img {
  max-width: 230px;
  cursor: pointer;
  position: relative;
  top: 0px;
}

.store-search {
  width: 55.6px;
  padding: 0 9px;
  border-radius: 0;
  border-radius: 3px;

  &:nth-child(2) {
    width: 55px;
    margin-left: -2px;
    border-radius: 3px;
  }
}

.btn-div {
  position: relative;
  height: 0px;
  top: -38px;
  left: 352px;
}

.history-list {
  margin-left: 28px;
}

.history-item {
  font-size: 13px;
  font-weight: normal;
  line-height: 16px;
  letter-spacing: 0px;
  margin-right: 17px;
  color: #666666;
  cursor: pointer;
}

:deep(.ivu-menu-horizontal) {
  height: 60px;
  line-height: 60px;
}

:deep(.ivu-menu-horizontal.ivu-menu-light:after) {
  background-color: #fff;
}
:deep(.top-menu) {
  margin-top: 10px;
  z-index: 5 !important;
  li.ivu-menu-submenu {
    padding: 0;
    padding-right: 10px;
    height: 60px;
    line-height: 60px;

    .ivu-menu-submenu-title {
      height: 60px;
      line-height: 60px;
      font-size: 18px;
      font-weight: 600;
      color: #333;
      z-index: -10;
    }

    &:hover {
      height: 65px;
      line-height: 65px;
      border-bottom:0 !important;
    }

    .ivu-select-dropdown .ivu-menu-item {
      padding: 7px 16px 8px;
      font-size: 16px !important;
    }
  }

  li.ivu-menu-item-active {
    border-bottom:0 !important;
  }

  li.ivu-menu-index {
    padding: 0;
    padding-right: 10px;
    height: 60px;
    line-height: 60px;
  }
}


</style>
